package com.ws.app.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ws.app.entity.Function;
import com.ws.app.service.FunctionService;
import com.ws.base.common.util.WSUtil;
import com.ws.base.db.common.order.Order;
import com.ws.base.db.support.DBSqlIdSupport;

public class FunctionServiceImpl implements FunctionService {
    private DBSqlIdSupport dbSqlIdSupport;

    @Override
    public List<Function> queryFuncByUserId(String userId) {
        List<Map<String, Object>> list = this.queryFunction(userId);
        return this.mToFunc(list);
    }

    @Override
    public List<Map<String, Object>> queryFuncMapByUserId(String userId) {
        List<Map<String, Object>> original = this.queryFunction(userId);
        List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
        Map<String, Object> tMap = null;

        for (Map<String, Object> map : original) {
            tMap = new HashMap<String, Object>();
            tMap.put("id", WSUtil.toStr(map.get("id")));
            tMap.put("text", WSUtil.toStr(map.get("name")));
            tMap.put("url", WSUtil.toStr(map.get("url")));
            tMap.put("expanded", true);
            tMap.put("leaf", true);
            newList.add(tMap);
        }
        return newList;

    }

    private List<Map<String, Object>> queryFunction(String userId) {
        Map<String, Object> condition = new HashMap<String, Object>();
        Order order = new Order();
        order.setAsc(true);
        order.setFieldName("PRIORITY");
        return dbSqlIdSupport.query("app_queryFunctionByUserId", condition,
                null, order);
    }

    private List<Function> mToFunc(List<Map<String, Object>> list) {
        List<Function> functions = new ArrayList<Function>();
        Function function = null;

        for (Map<String, Object> map : list) {
            function = new Function();
            function.setId(WSUtil.toStr(map.get("id")));
            function.setName(WSUtil.toStr(map.get("name")));
            function.setUrl(WSUtil.toStr(map.get("url")));
            function.setPriority(Integer.parseInt(map.get("priority")
                    .toString()));
            functions.add(function);
        }

        return functions;
    }

    public DBSqlIdSupport getDbSqlIdSupport() {
        return dbSqlIdSupport;
    }

    public void setDbSqlIdSupport(DBSqlIdSupport dbSqlIdSupport) {
        this.dbSqlIdSupport = dbSqlIdSupport;
    }

}
